package org.zero.concurrency.demo.example.synccontainer;

import lombok.extern.slf4j.Slf4j;
import org.zero.concurrency.demo.annotations.NotThreadSafe;

import java.util.List;
import java.util.Vector;

/**
 * @program: concurrency-demo
 * @description: 模拟并发执行
 * @author: 01
 * @create: 2018-10-14 00:01
 **/
@Slf4j
@NotThreadSafe
public class VectorExample2 {
    private static List<Integer> vector = new Vector<>();

    public static void main(String[] args) {

        while (true) {
            for (int i = 0; i < 10; i++) {
                vector.add(i);
            }

            Runnable thread1 = () -> {
                for (int i = 0; i < vector.size(); i++) {
                    vector.remove(i);
                }
            };

            Runnable thread2 = () -> {
                for (int i = 0; i < vector.size(); i++) {
                    // 当thread2想获取i=9的元素的时候，而thread1刚好将i=9的元素移除了，就会导致数组越界
                    vector.get(i);
                }
            };

            new Thread(thread1).start();
            new Thread(thread2).start();
        }
    }
}
